package helperx

import (
	"crypto"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/pem"
	"errors"
)

// RsaSha256VerifySign RSA crypto.SHA256 模式验签
func RsaSha256VerifySign(data []byte, sign []byte, Key []byte) bool {
	block, _ := pem.Decode(Key)
	publicInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return false
	}
	publicKey := publicInterface.(*rsa.PublicKey)
	myHash := sha256.New()
	myHash.Write(data)
	hashed := myHash.Sum(nil)
	result := rsa.VerifyPKCS1v15(publicKey, crypto.SHA256, hashed, sign)

	return result == nil
}

// 获取私钥
func setPriKey(privateKey []byte, pemType string) (*rsa.PrivateKey, error) {
	block, _ := pem.Decode(privateKey)
	if block == nil {
		return nil, errors.New("pem.Decode err")
	}

	switch pemType {
	case "pkcs8":
		private, err := x509.ParsePKCS8PrivateKey(block.Bytes)
		if err != nil {
			return nil, err
		}

		if _, ok := private.(*rsa.PrivateKey); !ok {
			return nil, errors.New("invalid private key")
		}

		return private.(*rsa.PrivateKey), nil
	case "pkcs1":
		private, err := x509.ParsePKCS1PrivateKey(block.Bytes)
		if err != nil {
			return nil, err
		}
		return private, nil
	default:
		return nil, errors.New("invalid pem type")
	}
}
